package nautilus.tank;

import java.net.URL;
import java.net.URISyntaxException;
import java.net.MalformedURLException;
import java.io.File;

import nautilus.tank.component.MainFrame;

public class MainApp {
	public static void main(String[] args){
	
		//TODO: initialize environments, parameters, path... to the app
		init();
		
		MainFrame gameFrame = new MainFrame();
		gameFrame.setVisible(true);
	}
	
	private static void init(){
		URL url;
		String extURL;      //  url.toExternalForm();

		// get an url
		try {
			//String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
			//String decodedPath = URLDecoder.decode(path, "UTF-8");
		
			url = MainApp.class.getProtectionDomain().getCodeSource().getLocation();
			  // url is in one of two forms
			  //        ./build/classes/   NetBeans test
			  //        jardir/JarName.jar  froma jar
		} catch (SecurityException ex) {
			url = MainApp.class.getResource(MainApp.class.getSimpleName() + ".class");
			// url is in one of two forms, both ending "/com/physpics/tools/ui/PropNode.class"
			//          file:/U:/Fred/java/Tools/UI/build/classes
			//          jar:file:/U:/Fred/java/Tools/UI/dist/UI.jar!
		}

		// convert to external form
		extURL = url.toExternalForm();

		// prune for various cases
		if (extURL.endsWith(".jar"))   // from getCodeSource
			extURL = extURL.substring(0, extURL.lastIndexOf("/"));
		else {  // from getResource
			String suffix = "/"+(MainApp.class.getName()).replace(".", "/")+".class";
			extURL = extURL.replace(suffix, "");
			if (extURL.startsWith("jar:") && extURL.endsWith(".jar!"))
				extURL = extURL.substring(4, extURL.lastIndexOf("/"));
		}

		// convert back to url
		try {
			url = new URL(extURL);
		} catch (MalformedURLException mux) {
			// leave url unchanged; probably does not happen
		}

		// convert url to File
		try {
			Constant.EXECUTING_FOLDER =  new File(url.toURI());
		} catch(URISyntaxException ex) {
			Constant.EXECUTING_FOLDER =  new File(url.getPath());
		}
		
		System.out.println("[DEBUG] " + Constant.EXECUTING_FOLDER.getAbsolutePath());
	}
}
